package controllers

import (
	"bitbucket.org/alanwhen/infant-experience-class/enums"
	"bitbucket.org/alanwhen/infant-experience-class/models"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/orm"
	"time"
)

type ArticleCategoryController struct {
	BaseController
}

func (u *ArticleCategoryController) Prepare() {
	u.BaseController.Prepare()
	u.checkAuthor("DataGrid")
}

func (u *ArticleCategoryController) Index() {
	u.Data["pageTitle"] = "文章分类"
	u.ActiveSidebarUrl()
	u.Data["canEdit"] = u.checkActionAuthor(u.controllerName, "Edit")
	u.Data["canDelete"] = u.checkActionAuthor(u.controllerName, "Delete")
	u.setTpl("article_category/index")
}

func (u *ArticleCategoryController) DataGrid() {
	var params models.CategoryQueryParam
	json.Unmarshal(u.Ctx.Input.RequestBody, &params)

	data, total := models.CategoryPageList(&params)
	u.BootstrapJson(total, data)
}

func (u *ArticleCategoryController) DataList() {
	var params = models.CategoryQueryParam{}

	data := models.CategoryDataList(&params)

	u.jsonResult(enums.JRCodeSuccess, "", data)
}

func (u *ArticleCategoryController) Edit() {
	if u.Ctx.Request.Method == "POST" {
		u.Save()
	}
	Id, _ := u.GetInt(":id", 0)

	m := &models.Category{}
	var err error

	if Id > 0 {
		m, err = models.CategoryOne(Id)
		if err != nil {
			u.pageError("数据无效，请刷新后重试")
		}
	} else {

	}
	u.Data["m"] = m

	u.setTpl("article_category/edit", "shared/layout_pullbox")
}

func (u *ArticleCategoryController) Save() {
	m := models.Category{}
	o := orm.NewOrm()
	var err error

	if err = u.ParseForm(&m); err != nil {
		u.jsonResult(enums.JRCodeFailed, "获取数据失败"+err.Error(), m.Id)
	}

	m.SysUser = &u.curUser

	if m.Id == 0 {
		m.AddTime = time.Now().Unix()
		if _, err := o.Insert(&m); err != nil {
			u.jsonResult(enums.JRCodeFailed, "添加失败"+err.Error(), m.Id)
		}
	} else {
		oM, err := models.CategoryOne(m.Id)
		if err != nil {
			u.jsonResult(enums.JRCodeFailed, "数据无效，请刷新后重试", m.Id)
		} else {
			m.AddTime = oM.AddTime
			if _, err := o.Update(&m); err != nil {
				u.jsonResult(enums.JRCodeFailed, "编辑失败", m.Id)
			}
		}
	}
	u.jsonResult(enums.JRCodeSuccess, "保存成功", m.Id)
}

func (u *ArticleCategoryController) Delete() {
	u.checkAuthor()
	Id, _ := u.GetInt("Id", 0)
	if Id == 0 {
		u.jsonResult(enums.JRCodeFailed, "所选的数据无效", 0)
	}

	query := orm.NewOrm().QueryTable(models.CategoryTBName())
	if _, err := query.Filter("id", Id).Delete(); err == nil {
		u.jsonResult(enums.JRCodeSuccess, fmt.Sprintf("删除成功"), 0)
	} else {
		u.jsonResult(enums.JRCodeFailed, "删除失败", 0)
	}
}
